﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using Entity.CommonEnums;
using Entity;
using Web.Attributes;
using Common.Background.Service;
using Common.Background.Entity;
using System.Xml.Xsl;
using System.Text;
using System.IO;
using VCommons;
using Web.Commons;

namespace Common.Background.Web.Controllers
{
    [UserAuthentication(AuthenticationType.BackgroundLogin)]
    public partial class SystemController : BackgroundBaseController
    {
        ISystemServices iSystemServices = null;
        IWebManageUserStrategyService iWebManageUserStrategyService = null;
        public SystemController()
        {
            iSystemServices = new SystemServices();
            iWebManageUserStrategyService = new WebManageUserStrategyService();
        }

        public ActionResult Index()
        {
            return View();
        }

        #region 员工管理

        const string TAG_ManageUserWebManageRoles = "WebManageRoles"; //表单中职位元素名称常量

        /// <summary>
        /// 填充页面上的部门和职位列表框和复选框
        /// </summary>
        /// <param name="WebManageUser"></param>
        private void iniSetWebManageUsers(WebManageUsers WebManageUser)
        {
            iniGetWebManageUsers(WebManageUser);
            List<WebManageRoles> WebManageRoles = null;

            List<WebDepartments> WebDepartments = iSystemServices.GetWebDepartments(new VPredication());
            if (WebDepartments != null && WebDepartments.Count > 0)
            {
                foreach (var i in WebDepartments)
                {
                    WebManageRoles = iSystemServices.GetWebManageRoles(i);
                    if (WebManageUser == null || WebManageUser.ManageUserID == int.MinValue || i.DepartmentID == WebManageUser.DepartmentID)
                    {
                        break;
                    }
                }
            }
            else
            {
                WebManageRoles = iSystemServices.GetWebManageRoles(new WebDepartments() { DepartmentID = WebManageUser.DepartmentID });
            }
            if (WebManageUser.WebManageUser_WebManageRoles_Extend == null)
            {
                WebManageUser.WebManageUser_WebManageRoles_Extend = new List<WebManageUser_WebManageRoles>().AsQueryable();
            }
            ViewData.Add("WebManageUserWebManageRoles", WebManageRoles);
            ViewData.Add("Departments", WebDepartments);
            ViewData.Add("WebManageUser_WebManageRoles", iSystemServices.GetWebManageUser_WebManageRoles(WebManageUser));
        }

        public ActionResult DepartmentForRole(string DeptId)
        {
            List<WebManageRoles> WebManageRoles = null;
            WebManageRoles = iSystemServices.GetWebManageRoles(new WebDepartments() { DepartmentID = Convert.ToInt32(DeptId) });
            ViewData.Add("WebManageUserWebManageRoles", WebManageRoles);
            return PartialView("DepartmentForRole", new List<WebManageUser_WebManageRoles>());
        }

        /// <summary>
        /// 初始化用户和职位的对应关系
        /// </summary>
        /// <param name="WebManageUser"></param>
        private void iniGetWebManageUsers(WebManageUsers WebManageUser)
        {
            if (WebManageUser.WebManageUser_WebManageRoles_Extend == null)
                WebManageUser.WebManageUser_WebManageRoles_Extend = new List<WebManageUser_WebManageRoles>().AsQueryable();
            if (Request[TAG_ManageUserWebManageRoles] != null && Request[TAG_ManageUserWebManageRoles].Length != 0)
            {
                int ManageRole;
                foreach (string i in Request[TAG_ManageUserWebManageRoles].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (int.TryParse(i, out ManageRole))
                    {
                        WebManageUser.WebManageUser_WebManageRoles_Extend.ToList().Add(new WebManageUser_WebManageRoles() { ManageUserID = WebManageUser.ManageUserID, ManageRoleID = ManageRole });
                    }
                }
            }
        }
        public ActionResult WebManageUserDetail(string id)
        {
            if (id == null || id.Length == 0)
            {
                id = Request["id"];
            }
            int Id;
            WebManageUsers model;
            if (int.TryParse(id, out Id))
            {
                model = iSystemServices.GetWebManageUsers(new WebManageUsers() { ManageUserID = Id });
            }
            else
            {
                model = new WebManageUsers() { ManageUserID = int.MinValue, DepartmentID = int.MinValue };
            }
            iniSetWebManageUsers(model);
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult WebManageUserDetail(FormCollection formCollection)
        {
            int Id;
            int.TryParse(formCollection["ManageUserID"], out Id);
            WebManageUsers entity = new Entity.WebManageUsers();

            UpdateModel(entity);
            entity.Operator = base.Current_UserName;

            this.iniSetWebManageUsers(entity);
            if (string.IsNullOrEmpty(formCollection["Password"]))
                entity.Password = string.Empty;
            else
                entity.Password = VCommons.Encryptor.Utility.EncryptString((formCollection["Password"]), VCommons.Encryptor.Utility.EncryptorType.MD5);
            entity.AvatarUrl = formCollection["AvatarUrl"] ?? string.Empty;
            entity.IntroductionURL = entity.IntroductionURL ?? string.Empty;
            entity.LoginNameSpell = string.Empty;
            entity.Status = Convert.ToInt32(formCollection["Status"]);
            List<WebManageUser_WebManageRoles> userRoleList = new List<WebManageUser_WebManageRoles>();
            string[] userRole = formCollection.GetValues("selRoleList") ?? new string[] { };
            //string[] userAuthority = formCollection.GetValues("OperatorAuthority") ?? new string[] { };
            //int authority = 0;
            //foreach (string i in userAuthority)
            //{
            //    authority += Convert.ToInt32(i);
            //}
            Array.ForEach(userRole, i =>
            {
                userRoleList.Add(new WebManageUser_WebManageRoles { ManageRoleID = Convert.ToInt32(i) });
            });
            entity.WebManageUser_WebManageRoles_Extend = userRoleList.AsQueryable();
            try
            {
                if (entity.ManageUserID == int.MinValue)
                {
                    iSystemServices.WebManageUserAdd(entity);
                }
                else
                {
                    entity = iSystemServices.GetWebManageUsers(entity.ManageUserID);
                    string olderpass = entity.Password;
                    if (olderpass == null) olderpass = string.Empty;
                    UpdateModel(entity);
                    entity.Password = string.Empty;

                    if (formCollection["Password"] != olderpass)
                        entity.Password = VCommons.Encryptor.Utility.EncryptString(formCollection["Password"].ToString(), VCommons.Encryptor.Utility.EncryptorType.MD5);
                    else
                        entity.Password = olderpass;

                    userRoleList.ForEach(i => { i.ManageUserID = entity.ManageUserID; });
                    entity.WebManageUser_WebManageRoles_Extend = userRoleList;
                    entity.Operator = base.Current_UserName;
                    entity.AvatarUrl = formCollection["AvatarUrl"];
                    entity.IntroductionURL = formCollection["IntroductionURL"] ?? string.Empty;
                    entity.Status = Convert.ToInt32(formCollection["Status"]);
                    entity.UpdateDate = DateTime.Now;
                    iSystemServices.WebManageUserModify(entity);
                    entity.WebManageUser_WebManageRoles_Extend = iSystemServices.GetWebManageUser_WebManageRoles(new WebManageUsers { ManageUserID = Id });
                }

                UserOperatorRole userOperatorRole = UserOperatorRole.NoneAny;
                entity.WebManageUser_WebManageRoles_Extend.ToList().ForEach(i =>
                {
                    if (i.WebManageUsers_Extend != null)
                        userOperatorRole |= (UserOperatorRole)i.WebManageRoles_Extend.OperatorAuthority;
                });
                SessionAction.WriteSession("UserOperatorRole", (int)userOperatorRole);



                TempData["msg"] = DisplayMsg("操作成功", "/System/WebManageUserList");
            }
            catch (Exception)
            {
                throw;
            }
            return RedirectToAction("WebManageUserList");
        }

        public JsonResult GetRole(int DeptId)
        {
            JsonResult json = new JsonResult();
            List<WebManageRoles> linq = iSystemServices.GetWebManageRoles(new WebDepartments() { DepartmentID = DeptId });
            json.Data = new { list = linq };
            return json;
        }

        const string TAG_RoleNames = "RoleName";
        const string TAG_DepartmentID = "DepartmentID";

        public ActionResult WebManageUserList(int? departmentID, int? roleID, string name, int? page)
        {
            #region 部门绑定

            List<WebDepartments> list = iSystemServices.WebDepartmentsList(new WebDepartments(), new VPredication());
            list.Insert(0, new WebDepartments() { DepartmentID = -1, DepartmentName = "全部" });
            SelectList select = new SelectList(list, "DepartmentID", "DepartmentName", "");
            ViewData["Dept"] = select;

            List<WebManageRoles> rolelist = iSystemServices.GetWebManageRoles(new WebDepartments() { DepartmentID = Convert.ToInt32(departmentID) });
            rolelist.Insert(0, new WebManageRoles() { ManageRoleID = -1, RoleName = "全部" });
            SelectList roleselect = new SelectList(rolelist, "ManageRoleID", "RoleName", "");
            ViewData["Role"] = roleselect;

            ViewData["name"] = name;

            #endregion 部门绑定

            #region 查询条件赋值

            VPredication vp = new VPredication();
            global::Entity.PagingParam pp = new global::Entity.PagingParam(page ?? 1, PageSize);
            if (departmentID.HasValue && departmentID != -1)
                vp.AddItem("departmentID", departmentID);
            if (roleID.HasValue && roleID != -1)
                vp.AddItem("roleID", roleID);
            if (!string.IsNullOrEmpty(name))
                vp.AddItem("name", name);

            #endregion 查询条件赋值

            PagedList<WebManageUsers> li = iSystemServices.GetWebManageUsers(vp, pp);
            li.AddParameters = new System.Collections.Specialized.NameValueCollection();
            li.AddParameters.Add("departmentID", departmentID.ToString());
            li.AddParameters.Add("roleID", roleID.ToString());
            li.AddParameters.Add("name", name);
            ViewData["WebManageUserList"] = li;
            return View();
        }

        [HttpPost]
        public ActionResult delete(string pi, string idd)
        {
            System.Web.Routing.RouteValueDictionary data = new System.Web.Routing.RouteValueDictionary();
            data.Add("page", pi);
            string[] idlist = idd.Split(',');
            List<WebManageUsers> list = new List<WebManageUsers>();
            foreach (var item in idlist)
            {
                list.Add(new WebManageUsers() { ManageUserID = Convert.ToInt32(item) });
            }
            iSystemServices.WebManageUsersDelete(list);
            return RedirectToAction("WebManageUserList", data);
        }

        [HttpPost]
        public ActionResult Freeze(string pi, string idd)
        {
            System.Web.Routing.RouteValueDictionary data = new System.Web.Routing.RouteValueDictionary();
            data.Add("page", pi);
            string[] idlist = idd.Split(',');
            List<WebManageUsers> list = new List<WebManageUsers>();
            WebManageUsers users = null;
            foreach (var item in idlist)
            {
                users = iSystemServices.GetWebManageUsers(new WebManageUsers { ManageUserID = Convert.ToInt32(item) });
                users.Status = (int)Status.Freezed;
                list.Add(users);
            }
            iSystemServices.WebManageUserModify(list);
            return RedirectToAction("WebManageUserList", data);
        }

        [HttpPost]
        public ActionResult NotFreeze(string pi, string idd)
        {
            System.Web.Routing.RouteValueDictionary data = new System.Web.Routing.RouteValueDictionary();
            data.Add("page", pi);
            string[] idlist = idd.Split(',');
            List<WebManageUsers> list = new List<WebManageUsers>();
            WebManageUsers users = null;
            foreach (var item in idlist)
            {
                users = iSystemServices.GetWebManageUsers(new WebManageUsers { ManageUserID = Convert.ToInt32(item) });
                users.Status = (int)Status.Normal;
                list.Add(users);
            }
            iSystemServices.WebManageUserModify(list);
            return RedirectToAction("WebManageUserList", data);
        }

        #endregion 员工管理

        #region 职位设置

        const string TAG_WebManageRolesWebManage = "ManageRolesWebManage";

        private void iniGetWebManageRolesWebManageMenus(WebManageRoles WebManageRoles)
        {
            List<WebManageRole_WebManageMenus> webManageRole_WebManageMenus_Extend = new List<WebManageRole_WebManageMenus>();
            if (!string.IsNullOrEmpty(Request[TAG_WebManageRolesWebManage]))
            {
                int Menus;
                foreach (string i in Request[TAG_WebManageRolesWebManage].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (int.TryParse(i, out Menus))
                    {
                        webManageRole_WebManageMenus_Extend.Add(new WebManageRole_WebManageMenus() { MenuID = Menus });
                    }
                }

                WebManageRoles.WebManageRole_WebManageMenus_Extend = webManageRole_WebManageMenus_Extend;
            }
        }

        private void iniSetWebManageRolesWebManageMenus(WebManageRoles WebManageRoles)
        {
            iniGetWebManageRolesWebManageMenus(WebManageRoles);
            ViewData.Add("WebManageMenusAll", iSystemServices.WebManageMenusTree());
            ViewData.Add("WebManageMenuselect", WebManageRoles.WebManageRole_WebManageMenus_Extend == null ? new List<WebManageRole_WebManageMenus>() : WebManageRoles.WebManageRole_WebManageMenus_Extend.ToList());
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult WebManageRoles(string id)
        {
            ViewData.Add("Departments", iSystemServices.WebDepartmentsList(new WebDepartments() { Operator = base.Current_UserName }, null));
            if (id == null || id.Length == 0)
            {
                id = Request["id"];
            }
            int Id;
            WebManageRoles model;
            if (int.TryParse(id, out Id))
            {
                model = iSystemServices.GetWebManageRoles(new WebManageRoles() { ManageRoleID = Id });
            }
            else
            {
                model = new WebManageRoles() { ManageRoleID = int.MinValue };
            }
            var droplist = new SelectList(iSystemServices.WebDepartmentsList(new WebDepartments() { Operator = base.Current_UserName }, null), "DepartmentID", "DepartmentName", model.ManageRoleID);
            ViewData.Add("droplist", droplist);
            iniSetWebManageRolesWebManageMenus(model);
            if (Request.IsAjaxRequest())
            {
                return PartialView("UCWebManageRoles", model);
            }
            else
            {
                return View(model);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult WebManageRoles(WebManageRoles WebManageRoles)
        {
            ViewData.Add("Departments", iSystemServices.WebDepartmentsList(new WebDepartments() { Operator = base.Current_UserName }, null));
            iniSetWebManageRolesWebManageMenus(WebManageRoles);
            WebManageRoles.Operator = base.Background_Current_UserName;
            WebManageRoles.Status = (int)Status.Normal;
            WebManageRoles.OperatorAuthority = (int)base.UserOperatorRole;
            if (WebManageRoles.ManageRoleID == int.MinValue)
            {
                iSystemServices.AddWebManageRoles(WebManageRoles);
            }
            else
            {
                iSystemServices.SetWebManageRoles(WebManageRoles);
            }
            if (Request.IsAjaxRequest())
                return Json(true);
            else
                return RedirectToAction("WebManageRolesList");
        }

        const string TAG_RoleName = "RoleName";
        const string TAG_ManageRoleID = "ManageRoleID";

        public ActionResult WebManageRolesList(int? pi)
        {
            WebManageRoles WebManageRoles = new WebManageRoles();
            if (Request[TAG_RoleNames] != null && Request[TAG_RoleNames].Length > 0)
            {
                WebManageRoles.RoleName = Request[TAG_RoleNames];
            }
            int DepartmentID = int.MinValue;
            if (Request[TAG_ManageRoleID] != null && Request[TAG_ManageRoleID].Length > 0)
            {
                int.TryParse(Request[TAG_ManageRoleID], out DepartmentID);
            }

            WebManageRoles.DepartmentID = DepartmentID;

            global::Entity.PagedList<WebManageRoles> PageList;
            PageList = iSystemServices.WebManageRolesList(WebManageRoles, null, new PagingParam(pi ?? 0, 20));
            if (Request.IsAjaxRequest())
            {
                return PartialView("UCWebManageRolesList", PageList);
            }
            else
            {
                var dropdata = iSystemServices.WebDepartmentsList(new WebDepartments() { Operator = base.Current_UserName }, null);
                dropdata.Insert(0, new WebDepartments() { DepartmentID = int.MinValue, DepartmentName = "所有部门" });
                var droplist = new SelectList(dropdata, "DepartmentID", "DepartmentName", DepartmentID);

                ViewData.Add("droplist", droplist);
                return View(PageList);
            }
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult DeleteWebManageRoles(string ids)
        {
            int Id;
            JsonResult jr;
            if (int.TryParse(ids, out Id))
            {
                iSystemServices.DeleteWebManageRoles(new WebManageRoles { ManageRoleID = Id });
                if (Request.IsAjaxRequest())
                {
                    jr = new JsonResult();
                    jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    jr.Data = true;
                    return jr;
                }
                else
                {
                    return RedirectToAction("WebManageRolesList");
                }
            }
            else
            {
                if (Request.IsAjaxRequest())
                {
                    jr = new JsonResult();
                    jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    jr.Data = false;
                    return jr;
                }
                else
                {
                    return RedirectToAction("WebManageRolesList");
                }
            }
        }

        #endregion 职位设置

        #region 职员修改

        //const string TAG_ManageUserWebManageRoles = "WebManageRoles";

        private void iniGetWebManageUsers1(WebManageUsers WebManageUser)
        {
            if (WebManageUser.WebManageUser_WebManageRoles_Extend == null)
                WebManageUser.WebManageUser_WebManageRoles_Extend = new List<WebManageUser_WebManageRoles>().AsQueryable();
            if (Request[TAG_ManageUserWebManageRoles] != null && Request[TAG_ManageUserWebManageRoles].Length != 0)
            {
                int ManageRole;
                foreach (string i in Request[TAG_ManageUserWebManageRoles].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (int.TryParse(i, out ManageRole))
                    {
                        WebManageUser.WebManageUser_WebManageRoles_Extend.ToList().Add(new WebManageUser_WebManageRoles() { ManageUserID = WebManageUser.ManageUserID, ManageRoleID = ManageRole });
                    }
                }
            }
        }

        private void iniSetWebManageUsers1(WebManageUsers WebManageUser)
        {
            iniGetWebManageUsers(WebManageUser);
            List<WebManageRoles> WebManageRoles = null;

            List<WebDepartments> WebDepartments = iSystemServices.WebDepartmentsList(new WebDepartments() { DepartmentID = WebManageUser.DepartmentID }, new VPredication());
            if (WebDepartments != null && WebDepartments.Count > 0)
            {
                foreach (var i in WebDepartments)
                {
                    WebManageRoles = iSystemServices.WebManageRolesList(i);
                    if (WebManageUser == null || WebManageUser.ManageUserID == int.MinValue || i.DepartmentID == WebManageUser.DepartmentID)
                    {
                        break;
                    }
                }
            }
            else
            {
                WebManageRoles = iSystemServices.WebManageRolesList(new WebDepartments() { DepartmentID = WebManageUser.DepartmentID });
            }
            if (WebManageUser.WebManageUser_WebManageRoles_Extend == null)
            {
                WebManageUser.WebManageUser_WebManageRoles_Extend = new List<WebManageUser_WebManageRoles>().AsQueryable();
            }
            ViewData.Add("WebManageUserWebManageRoles", WebManageRoles);
            ViewData.Add("Departments", WebDepartments);
        }

        public ActionResult WebManageUser_WebManageRole(int? id)
        {
            ViewData.Add("WebManageUserWebManageRoles", iSystemServices.WebManageRolesList(new WebDepartments() { DepartmentID = id ?? int.MinValue }));
            return PartialView("UCWebManageUserWebManageRoles", new List<WebManageUser_WebManageRoles>());
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult WebManageUsers(string id)
        {
            if (id == null || id.Length == 0)
            {
                id = Request["id"];
            }
            int Id;
            WebManageUsers model;
            if (int.TryParse(id, out Id))
            {
                model = iSystemServices.GetWebManageUsers(new WebManageUsers() { ManageUserID = Id });
            }
            else
            {
                model = new WebManageUsers() { ManageUserID = int.MinValue, DepartmentID = int.MinValue };
            }
            iniSetWebManageUsers(model);
            if (Request.IsAjaxRequest())
            {
                return PartialView("UCWebManageUsers", model);
            }
            else
            {
                return View(model);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult WebManageUsers(WebManageUsers WebManageUsers)
        {
            WebManageUsers.Operator = base.Current_UserName;
            WebManageUsers.WebManageUser_WebManageRoles_Extend = GetWebManageUser_WebManageRole().AsQueryable();

            if (string.IsNullOrEmpty(WebManageUsers.QQ))
            {
                WebManageUsers.QQ = "";
            }
            if (string.IsNullOrEmpty(WebManageUsers.MSN))
            {
                WebManageUsers.MSN = "";
            }
            if (string.IsNullOrEmpty(WebManageUsers.Rtx))
            {
                WebManageUsers.Rtx = "";
            }
            if (WebManageUsers.ManageUserID == int.MinValue)
            {
                iSystemServices.AddWebManageUsers(WebManageUsers);
            }
            else
            {
                iSystemServices.SetWebManageUsers(WebManageUsers);
            }
            if (Request.IsAjaxRequest())
            {
                return Json(true);
            }
            else
            {
                return RedirectToAction("WebManageUsersList");
            }
        }

        public ActionResult WebManageUsersList(int? pi)
        {
            var p = new WebManageUsers() { LoginName = Request["name"], RealName = Request["name"] };
            int intParse;
            if (Request[TAG_DepartmentID] != null && Request[TAG_DepartmentID].Length != 0 && int.TryParse(Request[TAG_DepartmentID], out intParse))
            {
                p.DepartmentID = intParse;
            }
            else
            {
                p.DepartmentID = int.MinValue;
            }
            if (Request[TAG_RoleName] != null && Request[TAG_RoleName].Length != 0 && int.TryParse(Request[TAG_RoleName], out intParse))
            {
                p.WebManageUser_WebManageRoles_Extend = new List<WebManageUser_WebManageRoles>().AsQueryable();
                p.WebManageUser_WebManageRoles_Extend.ToList().Add(new WebManageUser_WebManageRoles() { ManageRoleID = intParse });
            }
            global::Entity.PagedList<WebManageUsers> li = iSystemServices.WebManageUsersList(p, new VPredication() { }, new PagingParam(pi ?? 0, 20));
            if (Request.IsAjaxRequest())
            {
                return PartialView("UCWebManageUsersList", li);
            }
            else
            {
                iniSetWebManageUsers(new WebManageUsers() { DepartmentID = int.MinValue });
                return View(li);
            }
        }

        const string TAG_ManageUserID = "ManageUserID";

        private List<WebManageUsers> GetWebManageUser()
        {
            string ManageUserID = Request[TAG_ManageUserID];
            List<WebManageUsers> li = new List<WebManageUsers>();
            int intParse;
            if (ManageUserID != null && ManageUserID.Length > 0)
            {
                foreach (string i in ManageUserID.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (int.TryParse(i, out intParse))
                        li.Add(new WebManageUsers() { ManageUserID = intParse });
                }
            }
            return li;
        }

        private List<WebManageUser_WebManageRoles> GetWebManageUser_WebManageRole()
        {
            string WebManageRolesID = Request[TAG_ManageUserWebManageRoles];
            List<WebManageUser_WebManageRoles> li = new List<WebManageUser_WebManageRoles>();
            int intParse;
            if (WebManageRolesID != null && WebManageRolesID.Length > 0)
            {
                foreach (string i in WebManageRolesID.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (int.TryParse(i, out intParse))
                        li.Add(new WebManageUser_WebManageRoles() { ManageRoleID = intParse });
                }
            }
            return li;
        }

        public ActionResult DeleteWebManageUsers(string id)
        {
            iSystemServices.DeleteWebManageUsers(GetWebManageUser());
            if (Request.IsAjaxRequest())
            {
                JsonResult jr = new JsonResult();
                jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                jr.Data = true;
                return jr;
            }
            else
            {
                return RedirectToAction("WebManageUsersList");
            }
        }

        public ActionResult ChangeUserStatus()
        {
            string type = Request["t"];
            if (type == "f")
            {
                iSystemServices.FreezeWebManageUsers(GetWebManageUser());
            }
            else if (type == "u")
            {
                iSystemServices.UnFreezeWebManageUsers(GetWebManageUser());
            }
            else if (type == "d")
            {
                iSystemServices.DeleteWebManageUsers(GetWebManageUser());
            }
            if (Request.IsAjaxRequest())
            {
                return Json(true);
            }
            else
            {
                return RedirectToAction("WebManageUsersList");
            }
        }

        public ActionResult ChangePassword()
        {
            return View(new WebManageUsers());
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChangePassword(WebManageUsers WebManageUser)
        {
            WebManageUser.ManageUserID = base.Background_Current_UserID;
            iSystemServices.UpdatePassWord(Request["OldPassword"], WebManageUser);
            if (Request.IsAjaxRequest())
            {
                return Json(true);
            }
            else
            {
                return JavaScript("<script type=\"text/javascript\">alert(\"修改成功\")</script>");
            }
        }

        #endregion 职员修改

        #region 头像上传

        public ActionResult uploadheadpic()
        {
            return View();
        }

        [HttpPost]
        public ActionResult uploadheadpic(FormCollection formcollection)
        {
            FileUpload _FileUploadWebServices;
            _FileUploadWebServices = new FileUpload();

            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase file = Request.Files[0];
                VMessage vm = _FileUploadWebServices.Image(UpLoadType.Image, file);
                if (vm.IsComplete)
                    TempData["PicUrl"] = "{result:true,msg:\"" + vm[0].Replace("\"", "") + "\"}";
                else
                    TempData["PicUrl"] = "{result:false,msg:\"" + vm[0].Replace("\"", "") + "\"}";
            }
            return View();
        }

        #endregion 头像上传


        /// <summary>
        /// 登录信息管理列表
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult WebManageLoginList(int? page)
        {
            string userid = Request.QueryString["id"];
            int _userid;
            VP = new VPredication();
            VP.AddItem("ManageUserID", int.TryParse(userid, out _userid));
            PP = new PagingParam(page ?? 1, PageSize);
            PagedList<WebManageUser_Strategy> model = iWebManageUserStrategyService.WebManageUser_Strategy(VP, PP);
            return View(model);
        }

        public ActionResult WebManageLogin()
        {
            string id = Request.QueryString["id"];
            WebManageUser_Strategy model = iWebManageUserStrategyService.GetModel(TypeParse.StrToInt(id, 0));
            return View(model);
        }

        [HttpPost]
        public ActionResult WebManageLogin(FormCollection form)
        {
            string[] id = form.GetValues("id");
            string[] manageUserID = form.GetValues("manageUserID");//用户ID
            string[] IPArea = form.GetValues("IPArea");//IP地址
            string[] beginDate = form.GetValues("beginDate");//开始时间
            string[] endDate = form.GetValues("endDate");//结束时间
            string[] status = form.GetValues("status");//状态

            WebManageUser_Strategy entity = new WebManageUser_Strategy();
            int intResult = 0;
            DateTime time = DateTime.Now;
            if (TypeParse.GetInt32FromStringArray(status, 0, out intResult))
                entity.Status = intResult;
            if (TypeParse.GetInt32FromStringArray(manageUserID, 0, out intResult))
                entity.ManageUserID = intResult;
            entity.IPArea = TypeParse.GetStringFromStringArray(IPArea, 0);
            if (TypeParse.GetDateTimeFromStringArray(endDate, 0, out time))
                entity.EndDate = time;

            if (TypeParse.GetDateTimeFromStringArray(beginDate, 0, out time))
                entity.BeginDate = time;

            WebManageUser_Strategy model = iWebManageUserStrategyService.GetModel(TypeParse.StrToInt(id[0], 0));
            //修改
            if (model != null)
            {
                entity.CreateDate = model.CreateDate;
                entity.ID = model.ID;
                iWebManageUserStrategyService.UpdateStrategy(entity);
            }
            //添加
            else
            {
                entity.CreateDate = DateTime.Now;
                iWebManageUserStrategyService.InsertStrategy(entity);
            }
            return Redirect("/System/WebManageLogin?userid=" + manageUserID[0] + "&res=t&id=" + id[0] + "");
        }

        #region 部门设置
        public ActionResult WebDepartmentsList()
        {
            XmlDocument xd = new XmlDocument();
            xd.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?><root />");
            List<WebDepartments> List = iSystemServices.WebDepartmentsList(null, null);
            var linq = List.AsQueryable();
            foreach (WebDepartments i in linq.Where(item => item.ParentID == 0).OrderByDescending(item => item.SortNumber))
            {
                SerializeWebDepartments(xd.DocumentElement, i, linq);
            }


            XslCompiledTransform xct = new XslCompiledTransform(true);
            StringBuilder sb = new StringBuilder();
            XmlWriter xw = new XmlTextWriter(new StringWriter(sb));
            XsltArgumentList xal = new XsltArgumentList();
            xct.Load(System.AppDomain.CurrentDomain.BaseDirectory + "\\XSLT\\WebDepartments.xslt");

            xct.Transform(xd, null, xw);
            xd.LoadXml(sb.ToString());
            if (Request.IsAjaxRequest())
            {
                return PartialView("UCWebDepartmentsList", xd);
            }
            else
            {
                return View(xd);
            }
        }

        void SerializeWebDepartments(XmlNode xn, WebDepartments WebDepartments, IQueryable<WebDepartments> linq)
        {
            XmlNode xnWebDepartments = xn.OwnerDocument.CreateElement("WebDepartments");
            XmlAttribute xa;

            xa = xn.OwnerDocument.CreateAttribute("DepartmentID");
            xa.Value = WebDepartments.DepartmentID.ToString();
            xnWebDepartments.Attributes.Append(xa);

            xa = xn.OwnerDocument.CreateAttribute("DepartmentName");
            xa.Value = WebDepartments.DepartmentName;
            xnWebDepartments.Attributes.Append(xa);

            xa = xn.OwnerDocument.CreateAttribute("About");
            xa.Value = WebDepartments.About;
            xnWebDepartments.Attributes.Append(xa);

            foreach (WebDepartments i in linq.Where(item => item.ParentID == WebDepartments.DepartmentID).OrderByDescending(item => item.SortNumber))
            {
                SerializeWebDepartments(xnWebDepartments, i, linq);
            }
            xn.AppendChild(xnWebDepartments);
        }

        public ActionResult WebDepartments()
        {
            WebDepartments wd;
            string Id = Request["id"]; int id;
            string PId = Request["pid"]; int pid;

            if (Id != null && Id.Length > 0 && int.TryParse(Id, out id))
                wd = iSystemServices.GetWebDepartments(new WebDepartments() { DepartmentID = id });
            else if (PId != null && PId.Length > 0 && int.TryParse(PId, out pid))
                wd = new WebDepartments() { DepartmentID = int.MinValue, ParentID = pid };
            else
                wd = new WebDepartments() { DepartmentID = int.MinValue };
            if (Request.IsAjaxRequest())
            {
                return PartialView("UCWebDepartments", wd);
            }
            else
            {
                return View(wd);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult WebDepartments(FormCollection form)
        {

            WebDepartments entity = new WebDepartments();
            TryUpdateModel(entity);
            if (entity.DepartmentID == int.MinValue)
            {
                iSystemServices.AddWebDepartments(entity);
            }

            else
            {
                iSystemServices.SetWebDepartments(entity);
            }
            if (Request.IsAjaxRequest())
            {
                return Json(true);
            }
            else
            {
                return RedirectToAction("WebDepartmentsList");
            }
        }

        public ActionResult DeleteWebDepartments(string id)
        {
            int Id;
            if (id != null && id.Length > 0 && int.TryParse(id, out Id))
            {
                iSystemServices.DeleteWebDepartments(new WebDepartments() { DepartmentID = Id });
            }
            if (Request.IsAjaxRequest())
            {
                return Json(true);
            }
            else
            {
                return RedirectToAction("WebDepartmentsList");
            }
        }

        #endregion

        #region 菜单维护


        public ActionResult WebWebManageMenusList()
        {
            XmlDocument xd = new XmlDocument();
            xd.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?><root />");
            List<WebManageMenus> List = iSystemServices.WebManageMenusList(null, null);
            var linq = List.AsQueryable();
            var li = linq.Where(item => item.ParentID == 0).OrderBy(item => item.SortNumber);
            foreach (WebManageMenus i in linq.Where(item => item.ParentID == 0).OrderByDescending(item => item.SortNumber))
            {
                SerializeWebManageMenu(xd.DocumentElement, i, linq);
            }


            XslCompiledTransform xct = new XslCompiledTransform(true);
            StringBuilder sb = new StringBuilder();
            XmlWriter xw = new XmlTextWriter(new StringWriter(sb));
            XsltArgumentList xal = new XsltArgumentList();
            xct.Load(System.AppDomain.CurrentDomain.BaseDirectory + "\\XSLT\\WebManageMenus.xslt");

            xct.Transform(xd, null, xw);
            xd.LoadXml(sb.ToString());
            if (Request.IsAjaxRequest())
            {
                return PartialView("UCWebWebManageMenusList", xd);
            }
            else
            {
                return View(xd);
            }
        }

        void SerializeWebManageMenu(XmlNode xn, WebManageMenus WebManageMenu, IQueryable<WebManageMenus> linq)
        {
            XmlNode xnWebWebManageMenu = xn.OwnerDocument.CreateElement("WebManageMenus");
            XmlAttribute xa;

            xa = xn.OwnerDocument.CreateAttribute("WebManageMenusID");
            xa.Value = WebManageMenu.MenuID.ToString();
            xnWebWebManageMenu.Attributes.Append(xa);

            xa = xn.OwnerDocument.CreateAttribute("WebManageMenusName");
            xa.Value = WebManageMenu.MenuName;
            xnWebWebManageMenu.Attributes.Append(xa);

            xa = xn.OwnerDocument.CreateAttribute("About");
            xa.Value = WebManageMenu.About;
            xnWebWebManageMenu.Attributes.Append(xa);

            xa = xn.OwnerDocument.CreateAttribute("LinkURL");
            xa.Value = WebManageMenu.LinkUrl;
            xnWebWebManageMenu.Attributes.Append(xa);

            xa = xn.OwnerDocument.CreateAttribute("Status");
            xa.Value = WebManageMenu.Status.ToString();
            xnWebWebManageMenu.Attributes.Append(xa);

            foreach (WebManageMenus i in linq.Where(item => item.ParentID == WebManageMenu.MenuID).OrderBy(item => item.SortNumber))
            {
                SerializeWebManageMenu(xnWebWebManageMenu, i, linq);
            }
            xn.AppendChild(xnWebWebManageMenu);
        }

        public ActionResult WebManageMenus()
        {
            WebManageMenus wd;
            string Id = Request["id"]; int id;
            string PId = Request["pid"]; int pid;

            if (Id != null && Id.Length > 0 && int.TryParse(Id, out id))
                wd = iSystemServices.GetWebManageMenus(new WebManageMenus() { MenuID = id });
            else if (PId != null && PId.Length > 0 && int.TryParse(PId, out pid))
                wd = new WebManageMenus() { MenuID = int.MinValue, ParentID = pid };
            else
                wd = new WebManageMenus() { MenuID = int.MinValue };
            if (Request.IsAjaxRequest())
            {
                return PartialView("UCWebManageMenus", wd);
            }
            else
            {
                return View(wd);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult WebManageMenus(WebManageMenus WebManageMenu)
        {

            WebManageMenu.Operator = base.Current_UserName;

            if (WebManageMenu.MenuID == int.MinValue)
            {
                WebManageMenu.ManageUserID = base.Background_Current_UserID;
                iSystemServices.AddWebManageMenus(WebManageMenu);
            }
            else
            {
                WebManageMenus _entity = iSystemServices.GetWebManageMenus(new WebManageMenus { MenuID = WebManageMenu.MenuID });
                _entity.LinkUrl = WebManageMenu.LinkUrl;
                _entity.MenuLevel = WebManageMenu.MenuLevel;
                _entity.MenuName = WebManageMenu.MenuName;
                _entity.Operator = WebManageMenu.Operator;
                _entity.ParentID = WebManageMenu.ParentID;
                _entity.SortNumber = WebManageMenu.SortNumber;
                _entity.Status = WebManageMenu.Status;
                iSystemServices.SetWebManageMenus(_entity);
            }
            if (Request.IsAjaxRequest())
            {
                return Json(true);
            }
            else
            {
                return RedirectToAction("WebWebManageMenusList");
            }
        }

        public ActionResult DeleteWebManageMenus(string id)
        {
            int Id;
            if (id != null && id.Length > 0 && int.TryParse(id, out Id))
            {
                try
                {
                    iSystemServices.DeleteManageMenus(new WebManageMenus() { MenuID = Id });
                }
                catch (Exception)
                {
                }
            }
            if (Request.IsAjaxRequest())
            {
                JsonResult jr = new JsonResult();
                jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                jr.Data = true;
                return Json(jr);
            }
            else
            {
                return RedirectToAction("WebWebManageMenusList");
            }
        }


        #endregion
    }
}